package com.kchouse.homepage;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.MineCarItem;
import com.kchouse.bean.RemindsetItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

import static cn.finalteam.toolsfinal.DateUtils.formatDate;
import static cn.finalteam.toolsfinal.DateUtils.getTime;

public class RemindsetActivity extends BaseActivity implements View.OnClickListener {

    private RemindsetActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private ListView lv_item;
    private TextView tv_maintainTime;
    private TimePickerView pvTime;
    private MaintainTimeTimeSelect maintainTimeTimeSelect;//保养时间选择
    private Calendar selectedDate;
    private Calendar startDate;
    private Calendar endDate;
    private TextView tv_notifyTime;
    private NotifyTimeTimeSelect notifyTimeTimeSelect;
    private EditText et_carNumber;
    private EditText et_maintainDistance;
    private Button bt_add;
    private ArrayList<RemindsetItem> listRemind = new ArrayList<>();
    private LvAdapter adapter;
    private RemindsetItem item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remindset);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("提醒设置");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);


        lv_item = (ListView) findViewById(R.id.lv_item);

        adapter = new LvAdapter();
        lv_item.setAdapter(adapter);
        tv_maintainTime = (TextView) findViewById(R.id.tv_maintainTime);
        tv_maintainTime.setOnClickListener(this);
        tv_notifyTime = (TextView) findViewById(R.id.tv_notifyTime);
        tv_notifyTime.setOnClickListener(this);

        maintainTimeTimeSelect = new MaintainTimeTimeSelect();
        notifyTimeTimeSelect = new NotifyTimeTimeSelect();

        et_carNumber = (EditText) findViewById(R.id.et_carNumber);
        et_maintainDistance = (EditText) findViewById(R.id.et_maintainDistance);
        bt_add = (Button) findViewById(R.id.bt_add);
        bt_add.setOnClickListener(this);
    }

    /**
     * 初始化时间选择器
     *
     * @param selectedDate
     * @param startDate
     * @param endDate
     */
    private void intiTime(Calendar selectedDate, Calendar startDate, Calendar endDate, OnTimeSelectListener listener) {
        pvTime = new TimePickerBuilder(mContent, listener)
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
//                        .setContentSize(18)//滚轮文字大小
                .setTitleSize(18)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLACK)//确定按钮文字颜色
                .setCancelColor(Color.BLACK)//取消按钮文字颜色
                .setTitleBgColor(Color.parseColor("#2A7CB8"))//标题背景颜色 Night mode
                .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(selectedDate, endDate)//起始终止年月日设定
//                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
    }


    /**
     * 保养时间选择器
     */
    class MaintainTimeTimeSelect implements OnTimeSelectListener {
        @Override
        public void onTimeSelect(Date date, View v) {
            tv_maintainTime.setText(formatDate(date));
        }
    }

    /**
     * 保养时间选择器
     */
    class NotifyTimeTimeSelect implements OnTimeSelectListener {
        @Override
        public void onTimeSelect(Date date, View v) {
            tv_notifyTime.setText(formatDate(date));
        }
    }

    private void intiData() {
        selectedDate = Calendar.getInstance();
        startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);
        startDate.set(2018, 0, 1);
        endDate.set(2030, 11, 31);

        GetRemindList();
    }

    /**
     * 获取提醒设置列表
     */
    private void GetRemindList() {
        String url = API.GetRemindList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    listRemind.clear();
                    listRemind.addAll(JSONObject.parseArray(data.getString("maintainList"), RemindsetItem.class));
                    adapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    class LvAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listRemind.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            item = listRemind.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_reminditem, null);
            TextView tv_carNumber = (TextView) view.findViewById(R.id.tv_carNumber);
            tv_carNumber.setText(item.getCarNumber());
            TextView tv_maintainDistance = (TextView) view.findViewById(R.id.tv_maintainDistance);
            tv_maintainDistance.setText(item.getMaintainDistance()+"(km)");
            TextView tv_maintainTime = (TextView) view.findViewById(R.id.tv_maintainTime);
            tv_maintainTime.setText(item.getMaintainTime());
            TextView tv_notifyTime = (TextView) view.findViewById(R.id.tv_notifyTime);
            tv_notifyTime.setText(item.getNotifyTime());
            return view;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_maintainTime:
                intiTime(selectedDate, startDate, endDate, maintainTimeTimeSelect);
                pvTime.show();
                break;
            case R.id.tv_notifyTime:
                intiTime(selectedDate, startDate, endDate, notifyTimeTimeSelect);
                pvTime.show();
                break;
            case R.id.bt_add:
                if (TextUtils.isEmpty(et_carNumber.getText().toString())) {
                    ToastUtils.getInstanc(mContent).showToast("车牌号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(et_maintainDistance.getText().toString())) {
                    ToastUtils.getInstanc(mContent).showToast("保养里程不能为空");
                    return;
                }
                if (TextUtils.isEmpty(tv_maintainTime.getText().toString())) {
                    ToastUtils.getInstanc(mContent).showToast("保养时间不能为空");
                    return;
                }
                if (TextUtils.isEmpty(tv_notifyTime.getText().toString())) {
                    ToastUtils.getInstanc(mContent).showToast("提醒时间不能为空");
                    return;
                }
                PostAddRemind(et_carNumber.getText().toString(), et_maintainDistance.getText().toString(), tv_maintainTime.getText().toString(), tv_notifyTime.getText().toString());
                break;
        }
    }

    /**
     * 添加提醒设置
     */
    private void PostAddRemind(String carNumber, String maintainDistance, String maintainTime, String notifyTime) {
        String url = API.PostAddRemind;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        JSONObject ob = new JSONObject();
        ob.put("userId", MainActivity.userid);
        ob.put("carNumber", carNumber);
        ob.put("maintainDistance", maintainDistance);
        ob.put("maintainTime", maintainTime);
        ob.put("notifyTime", notifyTime);
        params.applicationJson(ob);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    ToastUtils.getInstanc(mContent).showToast("设置成功");
                    GetRemindList();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }
}
